package br.com.funaction.eventtcontrollerv2.controller;

import java.io.IOException;
import java.io.Serializable;
import java.sql.SQLException;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpSession;

import br.com.funaction.eventtcontrollerv2.entities.Franquia;
import br.com.funaction.eventtcontrollerv2.model.LoginDAO;

@RequestScoped
@ManagedBean
public class LoginMB implements Serializable{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	Franquia franquia = new Franquia();
	LoginDAO loginDAO = new LoginDAO();
	Boolean temCredencial = false;

	public void efetuaLogin() throws SQLException, IOException{
		
		temCredencial = loginDAO.verificaCredencial(franquia.getEmail(), franquia.getSenha());
		
		if(temCredencial){
			
			franquia = loginDAO.dadosFranquia(franquia.getEmail(), franquia.getSenha());
			
			FacesContext contexto = FacesContext.getCurrentInstance();
			HttpSession sessao = (HttpSession) contexto.getExternalContext().getSession(true);
			FacesContext.getCurrentInstance().getExternalContext().getSessionMap().put("franquia", franquia);
			sessao.setAttribute("ID", franquia.getId());
			sessao.setAttribute("email", franquia.getEmail());
			
			ExternalContext contextoExterno = contexto.getExternalContext();
			contextoExterno.redirect("/eventt-controller-v2/index.jsf");
		} else{
			
			FacesContext contexto = FacesContext.getCurrentInstance();
			
			contexto.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "Erro!", "Login ou senha inválidos"));
		}
	}
	
	public Franquia getFranquia() {
		return franquia;
	}

	public void setFranquia(Franquia franquia) {
		this.franquia = franquia;
	}
	
}